<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\MobilePackage as MobilePackageModel;;
use think\Config;

/**
 * 手机套餐
 */
class MobilePackage extends Api
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    //手机套餐列表
    public function list(){
        $data  = MobilePackageModel::where('deletetime','NULL')->select();
        $this->success('获取手机套餐列表成功',$data);
    }

    //开通手机套餐
    public function open(){
        $deviceid = $this->request->post('deviceid');
        $user_id = $this->auth->id;
        //查询是否开通

        //未开通-新增开通记录

        //已开通-返回

    }

    //套餐购买记录
    public function orderlist(){
        $user_id = $this->auth->id;
        $data  = model('app\api\model\wanlshop\PackageOrder')
            ->alias('po')
            ->join('mobile_package mp','po.package_id=mp.id','LEFT')
            ->where('user_id',$user_id)
            ->where('yz_package_order.status','eq','paid')
            ->order('id desc')
            ->field('po.*,mp.name')
            ->paginate()->each(function ($item,$key){
                $item['state'] = -1;
                $arr = model('app\api\model\wanlshop\WatchPackageRefund')->where('order_id',$item['id'])->find();
                if(!empty($arr)){
                    $item['state'] = $arr['state'];
                    $item['refuse_content'] = $arr['refuse_content'];
                }
                //可退金额
                $month = getMonth(date('Y-m-d',time()),date('Y-m-d',$item['paytime']));
                $kt_money = $item['payamount']-($item['payamount']/12)*($month+1);
                if($kt_money<=0.01){
                    $kt_money=0;
                }
                $item['kt_money'] = $kt_money;
                return $item;
            });
        $this->success('获取套餐购买记录成功',$data);
    }

    /**
     * 提交售后服务
     *
     * @ApiSummary  (WanlShop 手表套餐退款接口提交售后服务)
     * @ApiMethod   (POST)
     *
     */
    public function addApply()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params ? $params : ($this->error(__('非正常访问')));
            $user_id = $this->auth->id;
            $orderModel = model('app\api\model\wanlshop\PackageOrder');
            // 查询订单
            $order = $orderModel
                ->where(['id' => $params['order_id'], 'user_id' => $user_id])
                ->find();
            $order ? $order : $this->error(__('订单异常'));
            // 提交数据
            $refund = model('app\api\model\wanlshop\WatchPackageRefund');
            $refund->user_id = $user_id;
            $refund->order_id = $order['id'];
            // 1.0.8升级 添加业务类型
            $refund->price = $params['money'];
            $refund->images = $params['images'];
            $refund->refund_content = $params['refund_content'];
            // 保存
            if($refund->save()){
                $order->save(['refund_status' => 1, 'refund_id' => $refund->id],['id' => $params['order_id']]);  // 修改订单商品状态提交退款中,并更新退款ID
                // 写入日志
                $this->refundLog($refund->id, '提交'. '，退款金额：￥'. $refund->price .'元；退款理由：'. $refund->refund_content);
                $this->success('ok', $refund->id);
            }
            $this->error(__('网络异常'));
        }
        $this->error(__('非法请求'));
    }

    /**
     * 提交售后服务
     *
     * @ApiSummary  (WanlShop 手表套餐退款接口提交售后服务)
     * @ApiMethod   (POST)
     * 2021年7月9日08:54:29
     */
    public function editRefund()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params ? $params : ($this->error(__('非正常访问')));
            $user_id = $this->auth->id;
            // 查询退货
            $refund = model('app\api\model\wanlshop\WatchPackageRefund')
                ->where(['id' => $params['id'], 'user_id' => $user_id])
                ->find();
            $refund ? $refund : ($this->error(__('没找到退款信息')));
            // 更新退款
            $params['state'] = 0;

            $data = $refund->update($params);
            // 写入日志
            $this->refundLog($refund->id, '提交'. '，退款金额：￥'. $refund->price .'元；退款理由：'. $refund->refund_content);
            $this->success('ok', $data['id']);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 退款日志（方法内使用）
     *
     * @ApiSummary  (WanlShop 退款日志)
     * @ApiMethod   (POST)
     *
     * @param string $refund_id 退款ID
     * @param string $content 日志内容
     */
    private function refundLog($refund_id = 0, $content = '')
    {
        return model('app\api\model\wanlshop\WatchPackageRefundLog')->save([
            'user_id' => $this->auth->id,
            'refund_id' => $refund_id,
            'content' => $content
        ]);
    }

    /**
     * 提交退货快递
     *
     * @ApiSummary  (WanlShop 退款接口提交退货快递)
     * @ApiMethod   (POST)
     */
    public function toExpress()
    {
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params ? $params : ($this->error(__('非正常访问')));
            // 查询退货
            $refund = $this->getRefund($params['id']);
            // 更新退款
            $result = $refund->allowField(true)->save([
                'state' => 6,
                'express_name' => $params['express_name'],
                'express_no' => $params['express_no'],
                'returntime' => time()
            ]);
            // 写入日志
            $this->refundLog($refund['id'], '买家已退货，运单号：'.$params['express_no'].'，快递公司：'.$params['express_name']);
            $this->success('ok', $params['id']);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 查询退款（方法内使用）
     *
     * @ApiSummary  (WanlShop 查询退款)
     * @ApiMethod   (POST)
     *
     * @param string $refund_id 退款ID
     */
    private function getRefund($refund_id = 0)
    {
        $refund = model('app\api\model\wanlshop\WatchPackageRefund')
            ->where(['id' => $refund_id, 'user_id' => $this->auth->id])
            ->find();
        return  $refund ? $refund : ($this->error(__('没找到退款信息')));
    }


}
